package com.oocl.products.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.products.pojo.User;
import com.oocl.products.service.UserService;
import com.oocl.products.service.factory.UserServiceFactory;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService;
	
    public LoginServlet() {
    	userService = UserServiceFactory.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		
		if("".equals(name) || "".equals(pwd)){
			request.setAttribute("errorMsg", "用户名或密码不能为空");
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		
		User user = userService.login(name, pwd);
		if(user!=null){
			request.getSession().setAttribute("user", user);
			response.sendRedirect("sec/product");
		}else{
			request.setAttribute("errorMsg", "用户名或密码不正确");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
